// const app = require('express')()

//导入数据库操作模块
const db = require("../../db/index.js")

//取jwt的密钥
const config = require('../../config')
const jwtSecretKey = config.jwtSecretKey
// 格式化时间
var moment = require('moment')
//导入uuid模块
const uuid = require('node-uuid')

//引入token 
var vertoken = require('../../utils/token/token')

//导入bcrypt包进行解密
const bcrypt = require('bcryptjs')

const jwt = require('jsonwebtoken')

/**
 * 管理员登录
 * @param {*} req 
 * @param {*} res 
 * @returns 
 */
exports.login = async (req, res) => {
    var admin_info = req.body
    // console.log(admin_info)
    if (!admin_info) {
        console.log('【登录失败】' + 'req.body ===> ', req.body)
        return res.send({
            code: 400,
            msg: '因发送的请求语法错误,服务器无法正常读取。',
            data: {}
        })
    }
    if (admin_info.account === '' || admin_info.password === '') {
        console.log('【登录失败】' + 'req.body ===> ', req.body)
        return res.send({
            code: 401,
            msg: '用户名或密码为空',
            data: {}
        })
    }
    //定义sql语句，查询用户
    const sql = 'SELECT * FROM xks_admin WHERE account = ? AND status != 0';
    await db.query(sql, admin_info.account, (err, results) => {
        if (err) {
            console.log('【登录失败】' + 'req.body ===> ', req.body)
            return res.send({
                code: 505,
                msg: err.message,
                data: {}
            })
        }

        const pwdMatchFlag = bcrypt.compareSync(admin_info.password, !results.length > 0 ? '' : results[0].password);

        if (!results[0] || !pwdMatchFlag) {
            console.log('【登录失败】' + 'req.body ===> ', req.body)
            return res.send({
                code: 401,
                msg: '用户名或密码不正确！',
                data: {}
            })
        }

        //查看账号是否激活
        if (!results[0].status) {
            console.log('【登录失败】' + '账号未激活')
            return res.send({
                code: 403,
                msg: '登录失败，该账号处于未激活状态',
                data: {}
            })
        }

        // console.log('【登录成功】', results[0])

        //登录次数+1
        results[0].login_count++;
        const sqlLoginCount = 'UPDATE xks_admin SET login_count = ? WHERE account = ?'
        db.query(sqlLoginCount, [results[0].login_count, results[0].account], (err, res) => {
            if (err) {
                console.log('【增加登录次数失败】')
                return res.send({
                    code: 505,
                    msg: err.message,
                    data: {}
                })
            }
            // console.log('登录次数+1')
        })

        // const token = jwt.sign(admin_info, jwtSecretKey, { expiresIn: '1h' })
        console.log('管理员【' + results[0].name + '】登录成功 , ip ===> ' + req.ip)
        vertoken.setToken(results[0]).then(token => {
            // console.log('token===>', token)
            res.send({
                code: 200,
                msg: '登录成功',
                data: { token }
            })
        })
    })
}


/**
 * 获取管理员列表
 * @param {*} req 
 * @param {*} res 
 */
exports.getAdminList = (req, res) => {
    // console.log("req.body:", req.body)
    // console.log('req.query', req.query)
    // 判断是否有操作的权限
    // console.log('req.data,', req.data)
    const admin = req.data
    if (admin.level != 1) {
        console.log('没有权限，admin.level ===> ' + admin.level)
        return res.send({
            code: 403,
            msg: '对不起，没有权限！',
            data: {}
        })
    }
    let sql = ''
    let level = req.query.level
    let roles = ''
    console.log(req.query)
    if (level == 3) roles = '普通管理员'
    else if (level == 2) roles = '高级管理员'
    else if (level == 1) roles = '超级管理员'
    else roles = '全部'
    let name = req.query.name
    let size = parseInt(req.query.limit)
    let start = (parseInt(req.query.page) - 1) * size
    let sqlArr = []
    if (!name || name == "") {
        if (!roles || roles == "" || roles + "" == "全部") {
            sql = `SELECT COUNT(*) FROM xks_admin WHERE status != 0;
            SELECT * FROM xks_admin WHERE status != 0 limit ?,?`;
            sqlArr = [start, size]
        }
        else {
            sql = `SELECT COUNT(*) FROM xks_admin WHERE roles = ? AND status != 0;
            SELECT * FROM xks_admin WHERE roles = ? AND status != 0 limit ?,?`;
            sqlArr = [roles, roles, start, size]
        }

        db.query(sql, sqlArr, (err, results) => {
            if (err) {
                return res.send({
                    code: 505,
                    msg: '错误',
                    videos: {}
                })
            }
            // 计算总页数
            var allCount = results[0][0]['COUNT(*)'];
            // console.log('results[0],', results[0])
            var allPage = parseInt(allCount) / size;
            var pageStr = allPage.toString();
            // 不能被整除
            if (pageStr.indexOf('.') > 0) {
                allPage = parseInt(pageStr.split('.')[0]) + 1;
            }
            var list = results[1];
            return res.send({
                code: 200,
                msg: '成功',
                totalPages: allPage,
                total: allCount,
                currentPage: start + 1,
                data: list
            })
        })
    } else {
        if (!roles || roles == "" || roles == "全部") {
            sql = `SELECT COUNT(*) FROM xks_admin WHERE name LIKE concat('%',?, '%') AND status != 0;
            SELECT * FROM xks_admin WHERE name LIKE concat('%',?, '%') AND status != 0 limit ?,?`;
            sqlArr = [name, name, start, size]
        } else {
            sql = `SELECT COUNT(*) FROM xks_admin WHERE name LIKE concat('%',?, '%') AND roles = ? AND status != 0;
            SELECT * FROM xks_admin WHERE name LIKE concat('%',?, '%') AND roles = ? AND status != 0 limit ?,?`;
            sqlArr = [name, roles, name, roles, start, size]
        }
        db.query(sql, sqlArr, (err, results) => {
            if (err) {
                return res.send({
                    code: 505,
                    msg: '错误',
                    videos: {}
                })
            }
            // 计算总页数
            var allCount = results[0][0]['COUNT(*)'];
            // console.log('results[0],', results[0])
            var allPage = parseInt(allCount) / size;
            var pageStr = allPage.toString();
            // 不能被整除
            if (pageStr.indexOf('.') > 0) {
                allPage = parseInt(pageStr.split('.')[0]) + 1;
            }
            var list = results[1];
            return res.send({
                code: 200,
                msg: '成功',
                totalPages: allPage,
                total: allCount,
                currentPage: start + 1,
                data: list
            })
        })
    }
}


/**
 * 获取管理员信息
 * @param {*} req 
 * @param {*} res 
 */
exports.getInfo = async (req, res) => {
    const admin = req.data
    admin.roles = [admin.roles]
    const sql = 'select * from xks_admin WHERE account = ? AND status != 0';
    await db.query(sql, admin.account, (err, results) => {
        if (err) {
            return res.send({
                code: 505,
                msg: '错误',
                data: {}
            })
        }
        if (results.length <= 0) {
            return res.send({
                code: 404,
                msg: '没有找到数据',
                data: {}
            })
        }
        // console.log('获取到了信息')
        results[0].roles = [results[0].roles]
        return res.send({
            code: 200,
            msg: '成功',
            data: results[0]
        })
    })
}

/**
 * 退出登录
 * @param {*} req 
 * @param {*} res 
 */
exports.logout = (req, res) => {
    console.log(req.data.name + '退出登录')
    jwt.verify(req.token, jwtSecretKey, (err, data) => {
        if (!err) {
            res.send({
                code: 200,
                msg: '退出登录',
                data: {}
            })
        } else {
            console.log('退出登录')
            res.send({
                code: 401,
                msg: '尚未登录，请先登录！',
                data: {}
            })
        }
    })
}



/**
 * 增加管理员
 * @param {*} req 
 * @param {*} res 
 * @returns 
 */
exports.addAdmin = (req, res) => {
    // 判断是否有操作的权限
    const admin = req.data
    if (admin.level != 1) {
        console.log('没有权限，admin.level ===> ' + admin.level)
        return res.send({
            code: 403,
            msg: '对不起，没有权限！',
            data: {}
        })
    }
    const admin_info = req.body;
    if (JSON.stringify(admin_info) == "{}") {
        console.log('【增加管理员发送错误】' + 'req.body ===> ', req.body)
        return res.send({
            code: 400,
            msg: '因发送的请求语法错误,服务器无法正常读取。',
            data: {}
        })
    }
    else {
        if (!admin_info.account || !admin_info.name || !admin_info.password) {
            return res.send({
                code: 400,
                msg: '有必填字段未填，请重新操作。',
                data: {}
            })
        }
    }
    // 要求密码包括字母，数字，不许有空格，8位到16位：
    let regPwd = /^(?=\S*[a-z])(?=\S*\d)\S{8,16}$/;
    // console.log('密码校验：', regPwd.test(admin_info.password))
    if (!regPwd.test(admin_info.password)) {
        return res.send({
            code: 400,
            msg: '密码需包括字母，数字，不许有空格，且在8位到16位之间。',
            data: {}
        })
    }
    //检查账户是否已经存在
    const findSql = `SELECT * FROM xks_admin WHERE account = ?  AND status != 0`
    db.query(findSql, admin_info.account, (err, results) => {
        if (err) {
            console.log(err.message)
            return res.send({
                code: 505,
                msg: err.message,
                data: {}
            })
        }
        if (results.length > 0) {
            return res.send({
                code: 400,
                msg: '该账号已存在，请重新操作！',
                data: {}
            })
        }
        //该账号可用，添加管理员并对密码进行加密
        admin_info.password = bcrypt.hashSync(admin_info.password, 10)
        // console.log('加密后', admin_info)
        //生成uuid
        let uuid1 = uuid.v4()
        // 去除横线-
        uuid1 = uuid1.replace(/-/g, '');
        // 添加id
        admin_info['id'] = uuid1;
        //创建时间
        let nowTime = new Date()
        var formatTime = moment(nowTime).format('YYYY-MM-DD HH:mm')
        admin_info['create_time'] = formatTime;

        if (admin_info.roles == '超级管理员') admin_info['level'] = 1
        else if (admin_info.roles == '高级管理员') admin_info['level'] = 2
        else if (admin_info.roles == '普通管理员') admin_info['level'] = 3

        if (admin_info.level == 1) admin_info['roles'] = "超级管理员"
        else if (admin_info.level == 2) admin_info['roles'] = "高级管理员"
        else if (admin_info.level == 3) admin_info['roles'] = "普通管理员"

        const addSql = `INSERT INTO xks_admin SET ? `
        db.query(addSql, admin_info, (err, result) => {
            if (err) {
                console.log(err.message)
                return res.send({
                    code: 505,
                    msg: err.message,
                    data: {}
                })
            }
            if (result.affectedRows !== 1) {
                return res.send({
                    code: 500,
                    msg: '增加失败，请稍后再试！',
                    data: {}
                })
            }
            res.send({
                code: 200,
                msg: '增加成功',
                data: result.affectedRows
            })
        })
    })

}


/**
 * 删除管理员
 * @param {*} req 
 * @param {*} res 
 * @returns 
 */
exports.delAdmin = (req, res) => {
    // 判断是否有操作的权限
    const admin = req.data
    if (admin.level != 1) {
        console.log('【删除管理员】没有权限，admin.level ===> ' + admin.level)
        return res.send({
            code: 403,
            msg: '对不起，没有权限！',
            data: {}
        })
    }

    const admin_info = req.query;

    if (admin.account != 'xmj' && admin_info.account == 'xmj') {
        return res.send({
            code: 403,
            msg: '对不起，没有权限！',
            data: {}
        })
    }

    if (JSON.stringify(admin_info) == "{}") {
        console.log('【删除管理员发送错误】' + 'req.body ===> ', req.query)
        return res.send({
            code: 400,
            msg: '因发送的请求语法错误,服务器无法正常读取。',
            data: {}
        })
    }
    else {
        if (!admin_info.id) {
            return res.send({
                code: 400,
                msg: '有必填字段未填，请重新操作。',
                data: {}
            })
        }
    }

    const delSql = `UPDATE xks_admin SET status = 0 WHERE id = ?`
    db.query(delSql, admin_info.id, (err, result) => {
        if (err) {
            console.log(err.message)
            return res.send({
                code: 505,
                msg: err.message,
                data: {}
            })
        }
        if (result.affectedRows !== 1) {
            return res.send({
                code: 500,
                msg: '删除失败，请检查ID是否有误！',
                data: {}
            })
        }
        res.send({
            code: 200,
            msg: '删除成功！',
            data: {}
        })
    })

}

/**
 * 更新管理员
 * @param {*} req 
 * @param {*} res 
 * @returns 
 */
exports.updateAdmin = (req, res) => {
    // 判断是否有操作的权限
    const admin_info = req.body;
    const admin = req.data
    if (admin.level != 1 && admin_info.id != admin.id) {
        return res.send({
            code: 403,
            msg: '对不起，没有权限！',
            data: {}
        })
    }

    if (admin.account != 'xmj' && admin_info.account == 'xmj') {
        return res.send({
            code: 403,
            msg: '对不起，没有权限！',
            data: {}
        })
    }

    if (JSON.stringify(admin_info) == "{}") {
        console.log('【更新管理员发送错误】' + 'req.body ===> ', req.body)
        return res.send({
            code: 400,
            msg: '因发送的请求语法错误,服务器无法正常读取。',
            data: {}
        })
    }
    else {
        if (!admin_info.id || !admin_info.account || !admin_info.name || (admin_info.oldPassword != '' && admin_info.password == '') || (admin_info.password != '' && admin_info.oldPassword == '')) {
            return res.send({
                code: 400,
                msg: '有必填字段未填，请重新操作。',
                data: {}
            })
        }
    }



    // if (admin.account != 'xmj' && admin.id != admin_info.id) delete admin_info.password
    // if (admin_info.password && admin_info.password.length > 20) delete admin_info.password
    if (admin_info.password && admin_info.password == '') delete admin_info.password

    console.log(admin.name + '正在修改' + admin_info.name + '的信息')
    // 要求密码包括字母，数字，不许有空格，8位到16位：
    let regPwd = /^(?=\S*[a-z])(?=\S*\d)\S{8,16}$/;
    // console.log('password == ', admin_info.password)
    // console.log('密码校验：', regPwd.test(admin_info.password))
    if (admin_info.password != undefined && admin_info.password != '' && !regPwd.test(admin_info.password)) {
        return res.send({
            code: 400,
            msg: '密码需包括字母，数字，不许有空格，且在8位到16位之间。',
            data: {}
        })
    }
    //对密码进行加密
    if (admin_info.password != undefined && admin_info.password != '') admin_info.password = bcrypt.hashSync(admin_info.password, 10)

    //获取原来的账号
    let oldAccount = ''
    // console.log('admin_info111====>', admin_info)
    const findOld = `SELECT * FROM xks_admin WHERE id = ? AND status != 0`
    db.query(findOld, admin_info.id, (err, result1) => {
        if (err) {
            // console.log('111' + err.message)
            return res.send({
                code: 505,
                msg: err.message,
                data: {}
            })
        }
        // console.log(results[0])
        let flag = true
        oldAccount = result1[0].account

        if (admin_info.oldPassword && admin_info.oldPassword != '') {
            if (!bcrypt.compareSync(admin_info.oldPassword, !result1.length > 0 ? '' : result1[0].password)) {
                flag = false
                return res.send({
                    code: 403,
                    msg: '原密码不正确',
                    data: {}
                })
            }
        }

        if (flag) {
            const findSql = `SELECT * FROM xks_admin WHERE account = ? AND status != 0`
            db.query(findSql, admin_info.account, (err, result2) => {
                if (err) {
                    console.log(err.message)
                    return res.send({
                        code: 505,
                        msg: err.message,
                        data: {}
                    })
                }
                if (admin_info.account + '' != oldAccount + '' && result2.length > 0) {
                    return res.send({
                        code: 400,
                        msg: '该账号已存在，请重新操作！',
                        data: {}
                    })
                }

                // console.log('加密后', admin_info)
                // console.log('管理员更新成功')
                const id = admin_info.id
                delete admin_info.id
                delete admin_info.oldPassword
                if (admin_info.password == '') delete admin_info.password
                const updateSql = `UPDATE xks_admin SET ? WHERE id = ? AND status != 0`

                // console.log('最后的信息：', admin_info)

                db.query(updateSql, [admin_info, id], (err, result) => {
                    if (err) {
                        console.log(err.message)
                        return res.send({
                            code: 505,
                            msg: err.message,
                            data: {}
                        })
                    }
                    // console.log(result)
                    if (result.affectedRows !== 1) {
                        return res.send({
                            code: 500,
                            msg: '更新失败，请稍后再试！',
                            data: {}
                        })
                    }
                    return res.send({
                        code: 200,
                        msg: '更新成功',
                        data: {}
                    })
                })
            })
        }
    })
}






/**
 * 获取总数据量
 * @param {*} req 
 * @param {*} res 
 */
exports.getCountData = (req, res) => {
    const sql = `
            SELECT COUNT(*) FROM xks_video_history;
            SELECT
            count(*) AS num,
            Date(
                DATE_SUB(NOW(), INTERVAL 0 DAY)
            ) as date_day
        FROM
            xks_video_history
        WHERE
            Date(
                DATE_SUB(NOW(), INTERVAL 0 DAY)
            ) = DATE(date)
        UNION ALL
            SELECT
                count(*) AS num,
                Date(
                    DATE_SUB(NOW(), INTERVAL 1 DAY)
                ) as date_day
            FROM
                xks_video_history
            WHERE
                Date(
                    DATE_SUB(NOW(), INTERVAL 1 DAY)
                ) = DATE(date)
        UNION ALL
            SELECT
                count(*) AS num,
                Date(
                    DATE_SUB(NOW(), INTERVAL 2 DAY)
                )as date_day
            FROM
                xks_video_history
            WHERE
                Date(
                    DATE_SUB(NOW(), INTERVAL 2 DAY)
                ) = DATE(date)
        UNION ALL
            SELECT
                count(*) AS num,
                Date(
                    DATE_SUB(NOW(), INTERVAL 3 DAY)
                )as date_day
            FROM
                xks_video_history
            WHERE
                Date(
                    DATE_SUB(NOW(), INTERVAL 3 DAY)
                ) = DATE(date)
        UNION ALL
            SELECT
                count(*) AS num,
                Date(
                    DATE_SUB(NOW(), INTERVAL 4 DAY)
                )as date_day
            FROM
                xks_video_history
            WHERE
                Date(
                    DATE_SUB(NOW(), INTERVAL 4 DAY)
                ) = DATE(date)
        UNION ALL
            SELECT
                count(*) AS num,
                Date(
                    DATE_SUB(NOW(), INTERVAL 5 DAY)
                )as date_day
            FROM
                xks_video_history
            WHERE
                Date(
                    DATE_SUB(NOW(), INTERVAL 5 DAY)
                ) = DATE(date)
        UNION ALL
            SELECT
                count(*) AS num,
                Date(
                    DATE_SUB(NOW(), INTERVAL 6 DAY)
                )as date_day
            FROM
                xks_video_history
            WHERE
                Date(
                    DATE_SUB(NOW(), INTERVAL 6 DAY)
                ) = DATE(date);
    
            SELECT COUNT(*) FROM xks_application WHERE status != 0;
            
            SELECT COUNT(*) FROM xks_study_videos WHERE flag != 0;
            
            SELECT COUNT(*) FROM xks_study_data WHERE flag != 0;
            
            SELECT
                tags.tag_name AS name,COUNT(history.id) AS value 
            FROM
                xks_video_history AS history, xks_tags AS tags 
            WHERE
                tags.tag_type = '学习视频' AND history.v_id = tags.c_id AND flag != 0 
            GROUP BY
                tags.tag_name;


            SELECT tag_name AS name, COUNT(id) AS value
            FROM xks_tags
            GROUP BY tag_name;
            `
    db.query(sql, (err, results) => {
        if (err) {
            return res.send({
                code: 505,
                msg: '错误' + err,
                data: {}
            })
        }
        // console.log(results[0])
        // console.log(results[1])
        // console.log(results[2])
        // console.log(results[3])
        results[1].forEach(element => {
            element.date_day = moment(element.date_day).format('MM-DD')
        });

        // console.log(results)
        return res.send({
            code: 200,
            msg: '成功',
            data: {
                // results
                videosHosityCount: results[0][0]['COUNT(*)'],
                traffic: results[1],
                applyCount: results[2][0]['COUNT(*)'],
                videosCount: results[3][0]['COUNT(*)'],
                dataCount: results[4][0]['COUNT(*)'],
                VideosHosityCountBytags: results[5],
                tagsCount: results[6],
            }
        })
    })
}
